package org.tcx.web.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tcx.common.LogUtil;

public class PathResolveFilter implements Filter {
	private static Log log = LogFactory.getLog(PathResolveFilter.class);
	public void destroy() {
		log.debug("enter");
		// TODO Auto-generated method stub
		log.debug("leave");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		log.debug("enter"
				+ LogUtil.arg("request, response, chain", request, response,
						chain));
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String requestURI = httpRequest.getRequestURI();
		System.out.println(requestURI);
		Matcher matcher =Pattern.compile("^.*\\|-(.*)$").matcher(requestURI);
		if(matcher.matches()){
			log.debug(LogUtil.arg("matcher.group(1)",matcher.group(1)));
			httpRequest.getRequestDispatcher(matcher.group(1)).forward(request, response);
		}else{
			chain.doFilter(request, response);
		}
		log.debug("leave");
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		log.debug("enter" + LogUtil.arg("filterConfig", filterConfig));
		// TODO Auto-generated method stub
		log.debug("leave");
	}
}
